package com.example.wenqujingdian.activity;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.example.wenqujingdian.R;
import com.example.wenqujingdian.adapter.BookModelListAdapter;
import com.example.wenqujingdian.adapter.BookTypeAdapter;
import com.example.wenqujingdian.api.ApiConfig;
import com.example.wenqujingdian.bean.BookDetailBean;
import com.example.wenqujingdian.bean.BookSortBean;
import com.example.wenqujingdian.model.BookModelBean;
import com.example.wenqujingdian.utils.ToastUtil;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.vise.xsnow.http.ViseHttp;
import com.vise.xsnow.http.callback.ACallback;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

public class CloundBookActivity extends BaseActivity {
    private static final String TAG = "BookActivity";
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;

    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.title)
    TextView title;
    @BindView(R.id.recyclerViewType)
    RecyclerView recyclerViewType;
    @BindView(R.id.all_book)
    TextView allBook;

    @BindView(R.id.edit_search01)
    EditText editSearch01;
    @BindView(R.id.edit_search02)
    EditText editSearch02;
    @BindView(R.id.btn_search)
    Button btnSearch;
    @BindView(R.id.refresh)
    SmartRefreshLayout smartRefresh;

    private BookModelListAdapter mAdapter;
    private BookTypeAdapter typeAdapter;
    private ProgressDialog progressDialog;
    private List<BookModelBean.DataBean.ListBean> bookList;
    private boolean isRefresh;
    private int currentPage;
    private int classID = 199;
    private String editSearchContext = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_book2);
        ButterKnife.bind(this);

        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        title.setText("图书");

        progressDialog = new ProgressDialog(this);
        initView();
        initData();
    }

    private void initView() {
        GridLayoutManager manager;
        if (findViewById(R.id.tv_book2_land) != null) {
            //横屏显示
            manager = new GridLayoutManager(this, 5);
        } else {
            //竖屏显示
            manager = new GridLayoutManager(this, 3);
        }

        //manager.setOrientation(LinearLayoutManager.HORIZONTAL);
        recyclerView.setLayoutManager(manager);
        mAdapter = new BookModelListAdapter(this, null);
        mAdapter.openLoadAnimation();
        recyclerView.setAdapter(mAdapter);
        mAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                Log.i(TAG, "onItemClick: position=" + position);
                BookModelBean.DataBean.ListBean item = mAdapter.getItem(position);
                BookDetailBean bookDetailBean = new BookDetailBean();
                Intent intent = new Intent(CloundBookActivity.this, BookDetailsActivity.class);
                bookDetailBean.id = String.valueOf(item.getBookId());
                bookDetailBean.news_tit = item.getBookTitle();
                bookDetailBean.author = item.getAuthor();
                bookDetailBean.news_source = item.getPublisher();
                bookDetailBean.spic = item.getCover();
                bookDetailBean.url = item.getBookUrl();
                bookDetailBean.classId = item.getClassId();
                intent.putExtra("bookDetail", bookDetailBean);
                startActivity(intent);

              /*  Intent intent = new Intent(BookActivity.this, BookReadActivity.class);
                intent.putExtra("pdfurl", mAdapter.getItem(position).url);
                startActivity(intent);*/
            }
        });


        GridLayoutManager manager2;
        if (findViewById(R.id.tv_book2_land) != null) {
            //横屏显示
            manager2 = new GridLayoutManager(this, 5);
        } else {
            //竖屏显示
            manager2 = new GridLayoutManager(this, 3);
        }

        //manager.setOrientation(LinearLayoutManager.HORIZONTAL);
        recyclerViewType.setLayoutManager(manager2);
        typeAdapter = new BookTypeAdapter(this, null);
        typeAdapter.openLoadAnimation();
        recyclerViewType.setAdapter(typeAdapter);
        typeAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                Log.i(TAG, "onItemClick: position=" + position);
                BookSortBean.DataBean dataBean = typeAdapter.getItem(position);
             /*   Intent intent = new Intent(CloundBookActivity.this, BookSortListActivity.class);
                intent.putExtra("typeId", dataBean.getClassId());
                intent.putExtra("typeName", dataBean.getClassName());
                startActivity(intent);*/
                //切换分类
                bookList.clear();
                mAdapter.replaceData(bookList);
                classID = dataBean.getClassId();
                String className = dataBean.getClassName();
                title.setText(className);
                editSearch01.setText("");
                editSearchContext = "";
                smartRefresh.autoRefresh();
                //  autoRefresh();
            }
        });


        btnSearch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                editSearchContext = editSearch01.getText().toString().trim();
                if (TextUtils.isEmpty(editSearchContext)) {
                    ToastUtil.show("搜索的内容不能为空！");
                } else {
                    //ToastUtil.show("开发中...");
                    InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                    imm.hideSoftInputFromWindow(editSearch01.getWindowToken(), 0); //强制隐藏键盘

                    progressDialog.show();
//                    getSearchDataFromServer(editSearchContext);
                    currentPage = 0;
//                    getBookListData(currentPage, editSearchContext, classID);
                    getBookByNameDataJava(currentPage, editSearchContext, classID);
                }
            }
        });


    }


    private void initData() {
        progressDialog.setMessage("加载中...");
        progressDialog.show();
//        final long time1 = System.currentTimeMillis();
        setRefresh();
        bookList = new ArrayList<>();
        getBookListData(0, editSearchContext, classID);
    }

    private void setRefresh() {
        smartRefresh.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                autoRefresh();
                refreshLayout.finishRefresh(1000);
            }
        });
        smartRefresh.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                loadMore();
                refreshLayout.finishLoadMore(1000);
            }
        });
    }

    private void loadMore() {
        isRefresh = false;
        currentPage++;
        getBookListData(currentPage, editSearchContext, classID);
    }

    private void autoRefresh() {
        isRefresh = true;
        currentPage = 0;
        getBookListData(currentPage, editSearchContext, classID);
    }

    //获取图书列表数据
    private void getBookListData(final int pageIndex, final String search, int classID) {
        //判断搜索是否为空 , 如果为空则直接查找classid
        if (search.equals("")) {
            ViseHttp.GET(String.format(ApiConfig.YUN_CLASS_DETAIL, classID, currentPage))///90
                    .tag(TAG)
                    .baseUrl(ApiConfig.ORG_URL)
                    .setHttpCache(true)
                    //配置读取超时时间，单位秒
                    .readTimeOut(60)
                    //配置写入超时时间，单位秒
                    .writeTimeOut(60)
                    //配置连接超时时间，单位秒
                    .connectTimeOut(60)
                    //配置请求失败重试次数
                    .retryCount(3)
                    //配置请求失败重试间隔时间，单位毫秒
                    .retryDelayMillis(1000)
                    .request(new ACallback<BookModelBean>() {
                        @Override
                        public void onSuccess(BookModelBean bookListBeans) {
                            if (pageIndex == 0) {
                                getBookTypeData();
                            }
                            progressDialog.dismiss();
                            List<BookModelBean.DataBean> data = bookListBeans.getData();
                            if (data == null) return;
                            BookModelBean.DataBean dataBean = data.get(0);
//                            if(dataBean.getList().size()>0){
//                                dataBean.getList().remove(0);
//                            }
                            if (!search.equals("") && data == null && pageIndex == 0 && dataBean == null) {
                                ToastUtil.show("没有您想要的内容!");
                            }
                            if (dataBean == null) return;
                            if (isRefresh) {
                                bookList = dataBean.getList();
                                mAdapter.replaceData(bookList);
                            } else {
                                if (!search.equals("") && pageIndex == 0) {
                                    mAdapter.setNewData(dataBean.getList());
                                } else {
                                    bookList.addAll(dataBean.getList());
                                    mAdapter.addData(dataBean.getList());
                                }

                            }

                        }

                        @Override
                        public void onFail(int errCode, String errMsg) {
                            progressDialog.dismiss();
                            //请求失败，errCode为错误码，errMsg为错误描述
                            Log.i(TAG, "onFail: errCode" + " errMsg=" + errMsg);
                        }
                    });
        } else {
            ViseHttp.GET(String.format(ApiConfig.YUN_BOOK_LIST, search, pageIndex))///90
                    .tag(TAG)
                    .baseUrl(ApiConfig.ORG_URL)
                    .setHttpCache(true)
                    //配置读取超时时间，单位秒
                    .readTimeOut(60)
                    //配置写入超时时间，单位秒
                    .writeTimeOut(60)
                    //配置连接超时时间，单位秒
                    .connectTimeOut(60)
                    //配置请求失败重试次数
                    .retryCount(3)
                    //配置请求失败重试间隔时间，单位毫秒
                    .retryDelayMillis(1000)
                    .request(new ACallback<BookModelBean>() {
                        @Override
                        public void onSuccess(BookModelBean bookListBeans) {
                            if (pageIndex == 0 && search.equals("")) {
                                getBookTypeData();
                            }
                            if (!search.equals("")) {
                                bookList.clear();
                                progressDialog.dismiss();
                            }
                            List<BookModelBean.DataBean> data = bookListBeans.getData();
                            if (data == null) return;
                            BookModelBean.DataBean dataBean = data.get(0);
                            if (!search.equals("") && data == null && pageIndex == 0 && dataBean == null) {
                                ToastUtil.show("没有您想要的内容!");
                            }
                            if (dataBean == null) return;
                            if (isRefresh) {
                                bookList = dataBean.getList();
                                mAdapter.replaceData(bookList);
                            } else {
                                if (!search.equals("") && pageIndex == 0) {
                                    mAdapter.setNewData(dataBean.getList());
                                } else {
                                    bookList.addAll(dataBean.getList());
                                    mAdapter.addData(dataBean.getList());
                                }

                            }

                        }

                        @Override
                        public void onFail(int errCode, String errMsg) {
                            progressDialog.dismiss();
                            //请求失败，errCode为错误码，errMsg为错误描述
                            Log.i(TAG, "onFail: errCode" + " errMsg=" + errMsg);
                        }
                    });

        }
    }

    private void getBookTypeData() {
        //获取图书列表数据
        ViseHttp.GET(ApiConfig.YUN_BOOK_CLASS)
                .tag(TAG)
                .setHttpCache(true)
                //配置读取超时时间，单位秒
                .readTimeOut(60)
                //配置写入超时时间，单位秒
                .writeTimeOut(60)
                //配置连接超时时间，单位秒
                .connectTimeOut(60)
                //配置请求失败重试次数
                .retryCount(3)
                //配置请求失败重试间隔时间，单位毫秒
                .retryDelayMillis(1000)
                .request(new ACallback<BookSortBean>() {
                    @Override
                    public void onSuccess(BookSortBean sortBean) {
                        progressDialog.dismiss();
                        if (sortBean != null) {
                            List<BookSortBean.DataBean> data = sortBean.getData();
                            if (data != null && data.size() > 0) {
                                typeAdapter.setNewData(data);
                            }
                        } else {
                            Log.i(TAG, "onSuccess: bookListBeans is null");
                        }
                    }

                    @Override
                    public void onFail(int errCode, String errMsg) {
                        progressDialog.dismiss();
                        //请求失败，errCode为错误码，errMsg为错误描述
                        Log.i(TAG, "onFail: errCode" + " errMsg=" + errMsg);
                    }
                });


    }


    //获取图书列表数据
    private void getBookByNameDataJava(final int pageIndex, final String search, int classID) {
        //判断搜索是否为空 , 如果为空则直接查找classid
        String url="/wenqu/book/search?name=";
        if (search.equals("")) {
            ViseHttp.GET(String.format(ApiConfig.YUN_CLASS_DETAIL, classID, currentPage))///90
                    .tag(TAG)
                    .baseUrl(ApiConfig.ORG_URL)
                    .setHttpCache(true)
                    //配置读取超时时间，单位秒
                    .readTimeOut(60)
                    //配置写入超时时间，单位秒
                    .writeTimeOut(60)
                    //配置连接超时时间，单位秒
                    .connectTimeOut(60)
                    //配置请求失败重试次数
                    .retryCount(3)
                    //配置请求失败重试间隔时间，单位毫秒
                    .retryDelayMillis(1000)
                    .request(new ACallback<BookModelBean>() {
                        @Override
                        public void onSuccess(BookModelBean bookListBeans) {
                            if (pageIndex == 0) {
                                getBookTypeData();
                            }
                            progressDialog.dismiss();
                            List<BookModelBean.DataBean> data = bookListBeans.getData();
                            if (data == null) return;
                            BookModelBean.DataBean dataBean = data.get(0);
                            if (!search.equals("") && data == null && pageIndex == 0 && dataBean == null) {
                                ToastUtil.show("没有您想要的内容!");
                            }
                            if (dataBean == null) return;
                            if (isRefresh) {
                                bookList = dataBean.getList();
                                mAdapter.replaceData(bookList);
                            } else {
                                if (!search.equals("") && pageIndex == 0) {
                                    mAdapter.setNewData(dataBean.getList());
                                } else {
                                    bookList.addAll(dataBean.getList());
                                    mAdapter.addData(dataBean.getList());
                                }

                            }

                        }

                        @Override
                        public void onFail(int errCode, String errMsg) {
                            progressDialog.dismiss();
                            //请求失败，errCode为错误码，errMsg为错误描述
                            Log.i(TAG, "onFail: errCode" + " errMsg=" + errMsg);
                        }
                    });
        } else {
            ViseHttp.GET(url+search)///90
                    .tag(TAG)
                    .baseUrl(ApiConfig.SERVER_URL)
                    .setHttpCache(true)
                    //配置读取超时时间，单位秒
                    .readTimeOut(60)
                    //配置写入超时时间，单位秒
                    .writeTimeOut(60)
                    //配置连接超时时间，单位秒
                    .connectTimeOut(60)
                    //配置请求失败重试次数
                    .retryCount(3)
                    //配置请求失败重试间隔时间，单位毫秒
                    .retryDelayMillis(1000)
                    .request(new ACallback<BookModelBean>() {
                        @Override
                        public void onSuccess(BookModelBean bookListBeans) {
                            ToastUtil.show(bookListBeans.getMsg());
                            if (pageIndex == 0 && search.equals("")) {
                                getBookTypeData();
                            }
                            if (!search.equals("")) {
                                bookList.clear();
                                progressDialog.dismiss();
                            }
                            List<BookModelBean.DataBean> data = bookListBeans.getData();
                            if (data == null) return;
                            BookModelBean.DataBean dataBean = data.get(0);
                            if (!search.equals("") && data == null && pageIndex == 0 && dataBean == null) {
                                ToastUtil.show("没有您想要的内容!");
                            }
                            if (dataBean == null) return;
                            if (isRefresh) {
                                bookList = dataBean.getList();
                                mAdapter.replaceData(bookList);
                            } else {
                                if (!search.equals("") && pageIndex == 0) {
                                    mAdapter.setNewData(dataBean.getList());
                                } else {
                                    bookList.addAll(dataBean.getList());
                                    mAdapter.addData(dataBean.getList());
                                }

                            }

                        }

                        @Override
                        public void onFail(int errCode, String errMsg) {
                            progressDialog.dismiss();
                            //请求失败，errCode为错误码，errMsg为错误描述
                            Log.i(TAG, "onFail: errCode" + " errMsg=" + errMsg);
                        }
                    });

        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ViseHttp.cancelTag(TAG);
    }
}
